define([
    "dojo/_base/declare",
    "gistech/widgets/normalDialog/NormalDialog",
    "dojo/text!./templates/Template.html",
    "dojo/_base/lang",
    "dojo/topic",
    "dojo/dom-style",
    "dojo/dom-construct",
    "dojo/on",
    "dojo/_base/connect",
    "dojo/topic",
    "gistech/util/ajaxUtil",
    "dojo/dom-style","dojo/query","dojo/dom-class",],
    function(declare,NormalDialog,template,lang,topic,style,domConstruct,on,eventconnect,Topic,ajaxUtil,domStyle,query,domClass){
        return declare([NormalDialog],{
        templateString:template,
        container:null,
        constructor:function (args) {
        	this.inherited(arguments);
        	this.landTypeItem = (args.landTypeItem  != undefined) ? args.landTypeItem :null;
        	this.formId = (args.formId  != undefined) ? args.formId :null;
        	this.selNode=[];//存储选中的土地
        	this.isClose=false;//标识弹窗是否已经关闭
        },
        postCreate:function(){
            this.inherited(arguments);
            this.init();
            this.addEvents();
        },
        /**
         * 初始化
         */
        init:function () {
        	this.createLandResTree();
        	this.initLandResTreeDiagram();
        },
        /**
         * 添加事件
         */
        addEvents:function(){
        	on(this.dialogOk,"click",lang.hitch(this,this._okFun));
        },
        startup:function(){
            this.inherited(arguments);
        },
        /**
         * 关闭对话框
         */
        closeDialog:function(){
			this.inherited("closeDialog",arguments);
			this.destroy();
			isClose=true;
		},
        /**
         * 创建土地资源树
         */
        createLandResTree:function(){
//        	debugger
        	 if (window.goSamples) goSamples();  // init for these samples -- you don't need to call this
             var $ = go.GraphObject.make;  // for conciseness in defining templates
             this.myDiagram =
                $(go.Diagram, "heatDiagramDiv",  // must be the ID or reference to div
                 {
                 "toolManager.hoverDelay": 100,  // 100 milliseconds instead of the default 850
                 allowCopy: false, allowSelect: true,allowMove:false,allowResize:false,allowReshape:false,allowMove:false,allowRelink:false,allowDragOut:false,allowHorizontalScroll:false,
                 click:function(){
//                	 debugger
                     if(this.selNode.length != 0){
                         for(var i=0;i<this.selNode.length;i++){
                             if(!this.myDiagram.findNodeForKey(this.selNode[i]).isSelected){
                                 this.myDiagram.findNodeForKey(this.selNode[i]).isSelected=true;
                             }
                         }
                     }
                 }.bind(this),
                 LayoutCompleted:function(){
                     this.myDiagram.zoomToFit();
                 }.bind(this),
                 layout:  // create a TreeLayout for the family tree
                   $(go.TreeLayout,{ angle: 0, nodeSpacing: 10, layerSpacing: 40, layerStyle: go.TreeLayout.LayerUniform })
             });
             var graygrad = 'Silver';
             var pinkgrad = '#FFCCCC';
             var noStroke = null;
             var strokeStyle1='#5CACEE';
             var strokeStyle2='#FF6600';
             var sinRowHeight=50;
             var dobRowHeight=80;
             var threeRowHeight=120;
             //var selNode=[];
             // define Converters to be used for Bindings
             function genderBrushConverter(fillCol) {
                 if (fillCol === "noSel") return graygrad;
                 if (fillCol === "sel") return pinkgrad;
                 return "white";
             }
             function dsySetStroke(fillCol) {
                 if (fillCol === "noSel") return noStroke;
                 if (fillCol === "sel") return strokeStyle2;
                 return strokeStyle1;
             }
             function dsySetHeight(setHeight){
            	 switch(setHeight){
            	 	case "sinRowHeight":
            	 		return sinRowHeight;
            	 	case "dobRowHeight":
            	 		return dobRowHeight;
            	 	case "threeRowHeight":
            	 		return threeRowHeight
            	 }
             }
             // replace the default Node template in the nodeTemplateMapvar selNode=[];
             this.myDiagram.nodeTemplate =
             $(go.Node, "Auto",
                { click: function(e,obj){
//                	debugger
                    if(obj.je.fillCol == "sel" && obj.je.existData == true){
//                            debugger
                            if(this.selNode.length != 0){
                                var isExist=false;
                                for(var i=0;i<this.selNode.length;i++){
                                    if(this.selNode[i] == obj.je.key){
                                        isExist=true;
                                        obj.isSelected=false;
                                        this.selNode.remove(obj.je.key);
                                    }else{
                                        if(!this.myDiagram.findNodeForKey(this.selNode[i]).isSelected){
                                            this.myDiagram.findNodeForKey(this.selNode[i]).isSelected=true;
                                        }
                                    }
                                }
                                if(!isExist){
                                    this.selNode.push(obj.je.key);
                                }
                            }else{
                                this.selNode.push(obj.je.key);
                            }
                    }else{
                        obj.isSelected=false;
                        if(this.selNode.length != 0){
                            for(var i=0;i<this.selNode.length;i++){
                                if(!this.myDiagram.findNodeForKey(this.selNode[i]).isSelected){
                                    this.myDiagram.findNodeForKey(this.selNode[i]).isSelected=true;
                                }
                            }
                        }
                    }
                  }.bind(this)
                },
               { deletable: false/*,toolTip: tooltiptemplate */},
               new go.Binding("text", "name"),
               $(go.Shape, "RoundedRectangle",
                 { fill: "lightgray",
                   stroke: '#5CACEE', strokeWidth: 1.5,cursor:'pointer',width:200,
                   stretch: go.GraphObject.Fill,
                   alignment: go.Spot.Center},
                   new go.Binding("fill", "fillCol", genderBrushConverter),new go.Binding("stroke", "fillCol", dsySetStroke)),
                   new go.Binding("height", "setHeight", dsySetHeight),

               $(go.TextBlock,
                 { font: "200 17px 微软雅黑",
                   textAlign: "center",cursor:'pointer',
                   margin: 10, maxSize: new go.Size(120, NaN) },
                 new go.Binding("text", "name"))
             );
           // define the Link template
           this.myDiagram.linkTemplate =
             $(go.Link,  // the whole link panel
               { routing: go.Link.Orthogonal, corner: 5, selectable: false,resegmentable:false},
               $(go.Shape, { strokeWidth: 1, stroke: '#424242'}));  // the gray link shape
           // here's the family data
           var nodeDataArray = [
             { key: 0, name: "建设用地", fillCol:"general",setHeight:"sinRowHeight"},
            /*   { key: 1, parent: 0, name: "建设用地", fillCol:"general",setHeight:"sinRowHeight"},*/
                  /* { key: 11, parent: 1, name: "现状建设用地（有规模、有指标）",fillCol:"general"},*/
                       { key: 111, parent: 0, name: "国有建设用地",fillCol:"general",setHeight:"sinRowHeight"},
                           { key: 1111, parent: 111, name: "建成区",fillCol:"general",setHeight:"sinRowHeight"},
                               { key: 11111, parent: 1111, name: "非三旧建成区", fillCol: "noSel",setHeight:"sinRowHeight"},
                               { key: 11112, parent: 1111, name: "纳入三旧的旧厂", fillCol: "sel",existData:true,setHeight:"sinRowHeight"},
                               { key: 11113, parent: 1111, name: "纳入三旧的旧城", fillCol: "sel",existData:true,setHeight:"sinRowHeight"},
                           { key: 1112, parent: 111, name: "未建区",fillCol:"general",setHeight:"sinRowHeight"},
                               { key: 11121, parent: 1112, name: "国有储备用地", fillCol: "sel",existData:true,setHeight:"sinRowHeight"},
                               { key: 11122, parent: 1112, name: "已供未建地", fillCol: "noSel",setHeight:"sinRowHeight"},

                       { key: 112, parent: 0, name: "集体建设用地",fillCol:"general",setHeight:"sinRowHeight"},
                           { key: 1121, parent: 112, name: "建成区",fillCol:"general",setHeight:"sinRowHeight"},
                               { key: 11211, parent: 1121, name: "未纳入三旧的村", fillCol: "noSel",setHeight:"sinRowHeight"},
                               { key: 11212, parent: 1121, name: "纳入三旧的旧村", fillCol: "sel",existData:true,setHeight:"sinRowHeight"},
                               { key: 11213, parent: 1121, name: "未纳入三旧集体物业（工业、商业、仓储等）", fillCol: "noSel"},
                               { key: 11214, parent: 1121, name: "纳入三旧的集体旧厂", fillCol: "sel",existData:true},
                           { key: 1122, parent: 112, name: "未建区",fillCol:"general",setHeight:"sinRowHeight"},
                               { key: 11221, parent: 1122, name: "村自留地", fillCol: "sel",existData:true,setHeight:"sinRowHeight"},
                      { key: 113, parent: 0, name: "待征转用地（有规模、无指标）",fillCol:"general"},
                          { key: 1131, parent: 113, name: "违法建设用地", fillCol: "noSel",setHeight:"sinRowHeight"},
                          { key: 1132, parent: 113, name: "其他可征转用地", fillCol: "noSel",setHeight:"sinRowHeight"},

               /*{ key: 2, parent: 0, name: "非建设用地",fillCol:"general",setHeight:"sinRowHeight"},
                 { key: 21, parent: 2, name: "耕地、林地、园地、草地、其他农用地",fillCol:"general"},
                 { key: 22, parent: 2, name: "未利用地",fillCol:"general",setHeight:"sinRowHeight"},
                 { key: 23, parent: 2, name: "违法建设用地",fillCol:"general",setHeight:"sinRowHeight"}*/
           ];
           
           this.ableSelNode=[
                { key: 11112, parent: 1111, name: "纳入三旧的旧厂", fillCol: "sel",setHeight:"sinRowHeight"},
                { key: 11113, parent: 1111, name: "纳入三旧的旧城", fillCol: "sel",setHeight:"sinRowHeight"},
                { key: 11121, parent: 1112, name: "国有储备用地", fillCol: "sel",setHeight:"sinRowHeight"},
                { key: 11212, parent: 1121, name: "纳入三旧的旧村", fillCol: "sel",setHeight:"sinRowHeight"},
                { key: 11213, parent: 1121, name: "未纳入三旧集体物业（工业、商业、仓储等）", fillCol: "sel"},
                { key: 11214, parent: 1121, name: "纳入三旧的集体旧厂", fillCol: "sel",setHeight:"sinRowHeight"},
                { key: 11221, parent: 1122, name: "村自留地", fillCol: "sel",setHeight:"sinRowHeight"},
           ];
           // create the model for the family tree
           this.myDiagram.model = new go.TreeModel(nodeDataArray);
           debugger
           var divElm = query('#heatDiagramDiv > div',this.domNode)[0];
           var canvas= query('#heatDiagramDiv > canvas',this.domNode)[0];
           domStyle.set(divElm, "overflow", "");
           domStyle.set(canvas, "outline", "0");
           domStyle.set(canvas, "top", "3px");
           domStyle.set(canvas, "left", "30px");
        },
        _okFun:function(){
        	//格式化选中的节点
        	var formatSelNode=this.formatSelNode();
        	//为土地类型输入框赋值
        	this.toInputItemAssign(formatSelNode);
        	//关闭对话框
        	this.closeDialog();
        },
        //格式化选中的节点数组
        formatSelNode:function(){
        	var formatSelNode=[];
        	for(var i=0;i<this.selNode.length;i++){
        		for(var j=0; j<this.ableSelNode.length; j++){
            		if(this.selNode[i] == this.ableSelNode[j]["key"]){
            			formatSelNode.push(this.ableSelNode[j]["name"]);
            			break;
            		}
            	}
        	}
        	return  formatSelNode;
        },
        //为土地类型输入文本框赋值
        toInputItemAssign:function(formatSelNode){
        	if(formatSelNode.length != 0){
        		if(formatSelNode.length>1){
            		var selNodeStr=formatSelNode.join(" , ");
            		if(selNodeStr.length>8){
            			this.landTypeItem.val(selNodeStr.substring(0,8)+"...");
            			this.landTypeItem[0].title=selNodeStr;
            		}else{
            			this.landTypeItem.val(selNodeStr);
            			this.landTypeItem[0].title="";
            		}
            		Topic.publish('selMutilLandTypeNode_AdvQuery');//聚合详细信息
            	}else{
            		if(formatSelNode[0].length>8){
            			this.landTypeItem.val(formatSelNode[0].substring(0,8)+"...");
            			this.landTypeItem[0].title=formatSelNode[0];
            		}else{
            			this.landTypeItem.val(formatSelNode[0]);
            			this.landTypeItem[0].title="";
            		}
            		Topic.publish('selSingleLandTypeNode_AdvQuery');//聚合详细信息
            	}
        	}else{
        		this.landTypeItem.val("");
    			this.landTypeItem[0].title="";
        	}
        	//在为土地类型文本框赋完值后重新验证一下是否为空
        	if($(this.formId)!= null){
        		if($(this.formId).validate().element($(this.landTypeItem))){
        			$(this.landTypeItem).parent().removeClass('has-error');
        		}
        	}
        },
        //初始化土地资源树图表
        initLandResTreeDiagram:function(){
        	debugger
        	var formatSelNode=[];
        	var selNode=[];
//        	if(this.landTypeItem.val()!=""){
        	if(this.landTypeItem!=null && this.landTypeItem.val()!=""){
        		if(this.landTypeItem.val().indexOf("...")!=-1){
        			if(this.landTypeItem[0].title.replace(/\s/g,"").indexOf(",")!=-1){
        				selNode=this.landTypeItem[0].title.replace(/\s/g,"").split(",");
        			}else{
        				selNode.push(this.landTypeItem[0].title.replace(/\s/g,""));
        			}
        		}else{
        			if(this.landTypeItem.val().replace(/\s/g,"").indexOf(",")!=-1){
        				selNode=this.landTypeItem.val().replace(/\s/g,"").split(",");
        			}else{
        				selNode.push(this.landTypeItem.val().replace(/\s/g,""));
        			}
        		}
        		if(selNode.length != 0){
        			for(var i=0;i<selNode.length;i++){
                		for(var j=0; j<this.ableSelNode.length; j++){
                    		if(selNode[i] == this.ableSelNode[j]["name"]){
                    		    this.myDiagram.findNodeForKey(this.ableSelNode[j]["key"]).isSelected=true;
                    			formatSelNode.push(this.ableSelNode[j]["key"]);
                    			break;
                    		}
                    	}
                	}
        		}
        	}
        	this.selNode=formatSelNode;
        }
     });
});

